<template>
  <view>
    <cu-custom bgColor="bg-gradual-fff" isBack="true">
      <block slot="content">编辑商品</block>
    </cu-custom>
    
    <view class="edit-container">
      <!-- 商品图片 -->
      <view class="form-section">
        <view class="form-label">商品图片</view>
        <u-upload 
          :fileList="mainImageList" 
          @afterRead="handleMainImageUpload" 
          @delete="deleteMainImage"
          :maxCount="1"
          :previewFullImage="true"
        ></u-upload>
      </view>
      
      <!-- 商品基本信息 -->
      <view class="form-section">
        <view class="form-item">
          <view class="form-label">商品名称</view>
          <u-input v-model="editForm.name" placeholder="请输入商品名称" border="bottom"></u-input>
        </view>
        
        <view class="form-item">
          <view class="form-label">商品分类</view>
          <u-button @click="showCategoryPopup = true" plain>
            {{ selectedCategoryName || '请选择分类' }}
          </u-button>
        </view>
        
        <view class="form-item">
          <view class="form-label">销售价格</view>
          <u-input v-model="editForm.price" placeholder="请输入销售价格" type="number" border="bottom">
            <template #suffix>
              <text>积分</text>
            </template>
          </u-input>
        </view>
        
        <view class="form-item">
          <view class="form-label">原价</view>
          <u-input v-model="editForm.originalPrice" placeholder="请输入原价" type="number" border="bottom">
            <template #suffix>
              <text>积分</text>
            </template>
          </u-input>
        </view>
      </view>
      
      <!-- 商品描述 -->
      <view class="form-section">
        <view class="form-item">
          <view class="form-label">商品描述</view>
          <u-textarea 
            v-model="editForm.description" 
            placeholder="请输入商品详细描述"
            height="200"
          ></u-textarea>
        </view>
      </view>
      
      <!-- 保存按钮 -->
      <view class="submit-btn">
        <u-button type="primary" @click="submitEdit" :loading="submitting">保存修改</u-button>
      </view>
    </view>
    
    <!-- 分类选择弹窗 -->
    <u-popup :show="showCategoryPopup" mode="bottom" round="16" @close="showCategoryPopup = false">
      <view class="category-popup">
        <view class="popup-header">
          <text class="popup-title">选择分类</text>
          <u-icon name="close" @click="showCategoryPopup = false"></u-icon>
        </view>
        
        <scroll-view scroll-y class="category-list">
          <view 
            v-for="category in categories" 
            :key="category.id"
            class="category-item"
            :class="{active: editForm.categoryId === category.id}"
            @click="selectCategory(category)"
          >
            <text>{{ category.name }}</text>
            <u-icon v-if="editForm.categoryId === category.id" name="checkmark" color="#19BE6B"></u-icon>
          </view>
        </scroll-view>
        
        <view class="popup-footer">
          <u-button type="primary" @click="confirmCategory">确定</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import request from '@/common/request.js';
import storage from '@/common/storage.js';

export default {
  data() {
    return {
      id: 0,
      goodsinfo: {},
      submitting: false,
      showCategoryPopup: false,
      categories: [],
      selectedCategoryName: '',
      mainImageList: [],
      uploadUrl: request.baseUrl + 'api/file/upload',
      editForm: {
        name: '',
        categoryId: '',
        price: '',
        originalPrice: '',
        description: '',
        image: '',
		id:0
      }
    }
  },
  methods: {
    async getgoodsinfo() {
      try {
        const res = await request.httpRequest({
          url: `api/goods/${this.id}`,
          method: 'get'
        });
        
        if (res.data.code == 200) {
			console.log("商品",res.data.data)
          this.goodsinfo = res.data.data.goods;
          this.initFormData(res.data.data.goods);
        }
      } catch (err) {
        console.error('获取商品信息失败:', err);
        uni.showToast({ title: '获取商品信息失败', icon: 'none' });
      }
    },
    initFormData(data) {
      this.editForm = {
        name: data.name,
        categoryId: data.categoryId,
        price: data.price,
        originalPrice: data.originalPrice,
        description: data.description,
        image: data.image,
		id:this.id
      };
      if (data.categoryId && this.categories.length > 0) {
        const selectedCategory = this.categories.find(item => item.id === data.categoryId);
        this.selectedCategoryName = selectedCategory ? selectedCategory.name : '';
      }
      if (data.image) {
        this.mainImageList = [{
          url: request.baseUrl_img + data.image,
          status: 'success'
        }];
      }
    },
    async fetchCategories() {
      try {
        const res = await request.httpRequest({
          url: 'api/category/enabled',
          method: 'get'
        });
        
        if (res.data.code === 200) {
          this.categories = res.data.data;
          if (this.goodsinfo.id) {
            const selectedCategory = this.categories.find(item => item.id === this.goodsinfo.categoryId);
            this.selectedCategoryName = selectedCategory ? selectedCategory.name : '';
          }
        }
      } catch (error) {
        console.error('获取分类失败:', error);
        uni.showToast({ title: '获取分类失败', icon: 'none' });
      }
    },
    
    // 处理图片上传
    async handleMainImageUpload(event) {
      const file = event.file;
      this.mainImageList = [{
        ...file,
        status: 'uploading',
        message: '上传中...'
      }];
      
      try {
        const imgUrl = await this.uploadFilePromise(file.url, this.uploadUrl, 'main');
        this.mainImageList[0].status = 'success';
        this.mainImageList[0].message = '';
        this.mainImageList[0].url = imgUrl;
        this.editForm.image = imgUrl.replace(request.baseUrl_img, ''); // 保存相对路径
      } catch (error) {
        this.mainImageList[0].status = 'error';
        this.mainImageList[0].message = '上传失败';
        console.error('图片上传失败:', error);
        uni.showToast({ title: '图片上传失败', icon: 'none' });
      }
    },
    
    // 删除图片
    deleteMainImage() {
      this.mainImageList = [];
      this.editForm.image = '';
    },
    
    // 上传文件Promise封装
    uploadFilePromise(url, uploadUrl, type) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: uploadUrl,
          filePath: url,
          name: "file",
          formData: {
            user: "test",
          },
          success: (res) => {
            try {
              const result = JSON.parse(res.data);
              if (result.data && result.data.url) {
                resolve(request.baseUrl_img + result.data.url);
              } else {
                reject(new Error('未获取到图片URL'));
              }
            } catch (e) {
              reject(new Error('解析响应失败'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    
    // 选择分类
    selectCategory(category) {
      this.editForm.categoryId = category.id;
      this.selectedCategoryName = category.name;
    },
    
    // 确认分类选择
    confirmCategory() {
      if (!this.editForm.categoryId) {
        uni.showToast({ title: '请选择分类', icon: 'none' });
        return;
      }
      this.showCategoryPopup = false;
    },
    
    // 提交编辑
    async submitEdit() {
      if (!this.editForm.name) {
        uni.showToast({ title: '请输入商品名称', icon: 'none' });
        return;
      }
      
      if (!this.editForm.categoryId) {
        uni.showToast({ title: '请选择商品分类', icon: 'none' });
        return;
      }
      
      if (!this.editForm.price) {
        uni.showToast({ title: '请输入销售价格', icon: 'none' });
        return;
      }
      
      if (!this.editForm.image) {
        uni.showToast({ title: '请上传商品图片', icon: 'none' });
        return;
      }
      
      this.submitting = true;
      
      try {
        const res = await request.httpRequest({
          url: 'api/goods',
          method: 'put'
        },this.editForm);
        
        if (res.data.code === 200) {
          uni.showToast({ title: '修改成功' });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({ title: res.data.msg || '修改失败', icon: 'none' });
        }
      } catch (err) {
        console.error('修改商品失败:', err);
        uni.showToast({ title: '修改失败', icon: 'none' });
      } finally {
        this.submitting = false;
      }
    }
  },
  onLoad(option) {
    this.id = option.id;
    Promise.all([this.getgoodsinfo(), this.fetchCategories()]);
  }
}
</script>

<style lang="scss" scoped>
.edit-container {
  padding: 30rpx;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-item {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.submit-btn {
  margin-top: 60rpx;
  padding: 0 30rpx;
}

/* 分类弹窗样式 */
.category-popup {
  padding: 30rpx;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .popup-title {
    font-size: 32rpx;
    font-weight: bold;
  }
}

.category-list {
  flex: 1;
  margin-bottom: 30rpx;
  max-height: 50vh;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  
  &.active {
    color: #19BE6B;
  }
}

.popup-footer {
  padding-top: 20rpx;
  border-top: 1rpx solid #f5f5f5;
}

/* 调整uView组件样式 */
/deep/ .u-upload__wrap {
  margin-top: 10rpx;
}

/deep/ .u-textarea {
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
}
</style>